﻿using System;
using System.Collections.Generic;
using System.Configuration;

namespace Alex.Library.Log.Configuration
{
    /// <summary>
    /// 日志元素集合
    /// </summary>
    /// <typeparam name="T">日志类型</typeparam>
    public abstract class LoggerElementCollection<T> : ConfigurationElementCollection where T : ILogger
    {
        /// <summary>
        /// 创建新元素
        /// </summary>
        /// <returns></returns>
        protected override ConfigurationElement CreateNewElement()
        {
            if (typeof(T) == typeof(FileLogger))
            {
                return new FileLoggerElement();
            }
            else if (typeof(T) == typeof(ConsoleLogger))
            {
                return new ConsoleLoggerElement();
            }
            else if (typeof(T) == typeof(TraceLogger))
            {
                return new TraceLoggerElement();
            }
            else if (typeof(T) == typeof(XmlLogger))
            {
                return new XmlLoggerElement();
            }
            else if (typeof(T) == typeof(SmtpLogger))
            {
                return new MailLoggerElement();
            }
            else if (typeof(T) == typeof(CustomLogger))
            {
                return new CustomLoggerElement();
            }
            return null;
        }

        /// <summary>
        /// 用返回值作为element元素的键
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((LoggerElement)element).Name;
        }

        /// <summary>
        /// 获取指定集合类型
        /// </summary>
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }        

        /// <summary>
        /// 使用集合索引获取元素
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public virtual LoggerElement this[int index]
        {
            get
            {
                return (LoggerElement)BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }
    }
}
